package cn.itcast.hotel;

import cn.itcast.hotel.config.HotelConstants;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
public class EsIndexDemo {

    @Test
    public void createIndex() throws IOException {
        //2. 封装创建索引库的请求对象                              索引库名称
        CreateIndexRequest request = new CreateIndexRequest("hotel");
        // 整个请求参数的json字符串                                     指定参数类型JSON
        request.source(HotelConstants.MAPPING_TEMPLATE, XContentType.JSON);

        //3.调用客户端执行请求
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println("索引库创建结果:" + response.isAcknowledged());

    }

    @Test
    public void existIndex() throws IOException {
        //1.什么样的操作,就创建对应的请求对象
        GetIndexRequest request = new GetIndexRequest("hotel");
        // 调用客户端执行请求
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        //  解析响应结果
        System.out.println(exists ? "索引库存在" : "索引库不存在");
    }

    @Test
    public void deleteIndex() throws IOException {
        //1.什么样的操作,就创建对应的请求对象
        DeleteIndexRequest request = new DeleteIndexRequest("hotel");
        // 调用客户端执行请求
        AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
        //  解析响应结果
        System.out.println("是否删除成功:" + response.isAcknowledged());
    }


    RestHighLevelClient client;

    @BeforeEach
    public void init() {
        //1. 准备号客户端对象
        client = new RestHighLevelClient
                (RestClient.builder(HttpHost.create("http://192.168.200.130:9200")));

    }

    @AfterEach
    public void close() {
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
